
package com.shop.cloud.weixin.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.entity.BaseUser;
import com.shop.cloud.common.security.util.SecurityUtils;
import com.shop.cloud.weixin.admin.config.open.WxOpenConfiguration;
import com.shop.cloud.weixin.admin.service.WxAppService;
import com.shop.cloud.weixin.common.constant.WxConstant;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import com.shop.cloud.weixin.common.entity.WxApp;
import com.shop.cloud.weixin.common.entity.WxFastRegist;
import com.shop.cloud.weixin.admin.service.WxFastRegistService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.bean.auth.WxOpenAuthorizerInfo;
import me.chanjar.weixin.open.bean.mp.FastRegisterResult;
import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerInfoResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * 快速注册小程序
 *
 * @author 
 * @date 2022-02-24 11:55:42
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wxfastregist")
@Tag(description = "wxfastregist", name = "快速注册小程序管理")
public class WxFastRegistController {

    private final WxFastRegistService wxFastRegistService;
    private final WxAppService wxAppService;

    /**
     * 快速注册小程序分页列表
     * @param page 分页对象
     * @param wxFastRegist 快速注册小程序
     * @return
     */
    @Operation(summary = "快速注册小程序分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R getPage(Page page, WxFastRegist wxFastRegist) {
        return R.ok(wxFastRegistService.page(page, Wrappers.query(wxFastRegist)));
    }

    /**
     * 快速注册小程序查询
     * @param id
     * @return R
     */
    @Operation(summary = "快速注册小程序查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(wxFastRegistService.getById(id));
    }

    /**
     * 快速注册小程序新增
     * @param wxFastRegist 快速注册小程序
     * @return R
     */
    @Operation(summary = "快速注册小程序新增")
    @SysLog("新增快速注册小程序")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R save(@RequestBody WxFastRegist wxFastRegist) {
		BaseUser baseUser = SecurityUtils.getUser();
		if(CommonConstants.USER_TYPE_2.equals(baseUser.getType())){//店员
			wxFastRegist.setShopId(baseUser.getShopId());
		}else{
			wxFastRegist.setShopId(null);
		}
        return R.ok(wxFastRegistService.save(wxFastRegist));
    }

    /**
     * 快速注册小程序修改
     * @param wxFastRegist 快速注册小程序
     * @return R
     */
    @Operation(summary = "快速注册小程序修改")
    @SysLog("修改快速注册小程序")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R updateById(@RequestBody WxFastRegist wxFastRegist) {
		BaseUser baseUser = SecurityUtils.getUser();
		if(CommonConstants.USER_TYPE_2.equals(baseUser.getType())){//店员
			wxFastRegist.setShopId(baseUser.getShopId());
		}else{
			wxFastRegist.setShopId(null);
		}
        return R.ok(wxFastRegistService.updateById(wxFastRegist));
    }

    /**
     * 快速注册小程序删除
     * @param id
     * @return R
     */
    @Operation(summary = "快速注册小程序删除")
    @SysLog("删除快速注册小程序")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R removeById(@PathVariable String id) {
        return R.ok(wxFastRegistService.removeById(id));
    }

	/**
	 * 快速注册小程序查询状态
	 * @param id
	 * @return R
	 */
	@Operation(summary = "快速注册小程序查询状态")
	@GetMapping("/status/{id}")
	@PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
	public R getStatusById(@PathVariable("id") String id) {
		wxFastRegistService.getStatusById(id);
		return R.ok();
	}


    @Operation(summary = "复用公众号主体快速注册小程序")
    @SysLog("复用公众号主体快速注册小程序")
    @PostMapping("/mp/{appid}/{ticket}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxapp:add')")
    public R saveByMp(@PathVariable("appid") String appIdMp, @PathVariable("ticket") String ticket) {
        try {
            //复用公众号主体快速注册小程序
            FastRegisterResult fastRegisterResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMpServiceByAppid(appIdMp).fastRegister(ticket);
            String appIdMa = fastRegisterResult.getAppId();
            WxOpenConfiguration.getOpenService().getWxOpenComponentService().getQueryAuth(fastRegisterResult.getAuthorizationCode());
            //获取小程序信息
            WxOpenAuthorizerInfoResult wxOpenAuthorizerInfoResult = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getAuthorizerInfo(appIdMa);
            WxOpenAuthorizerInfo wxOpenAuthorizerInfo = wxOpenAuthorizerInfoResult.getAuthorizerInfo();
            WxApp wxApp = new WxApp();
            wxApp.setId(appIdMa);
            wxApp.setDelFlag(CommonConstants.STATUS_NORMAL);
            BaseUser baseUser = SecurityUtils.getUser();
            if(CommonConstants.USER_TYPE_2.equals(baseUser.getType())){//店员
                wxApp.setShopId(baseUser.getShopId());
            }else{
                wxApp.setShopId(null);
            }
            wxApp.setIsComponent(CommonConstants.YES);
            wxApp.setIsFastregist(WxConstant.WX_ISFASTREGIST_2);
            wxApp.setName(wxOpenAuthorizerInfo.getNickName());
            wxApp.setWeixinHao(wxOpenAuthorizerInfo.getAlias());
            wxApp.setWeixinSign(wxOpenAuthorizerInfo.getUserName());
            wxApp.setWeixinType(String.valueOf(wxOpenAuthorizerInfo.getServiceTypeInfo()));
            wxApp.setVerifyType(String.valueOf(wxOpenAuthorizerInfo.getVerifyTypeInfo()));
            wxApp.setLogo(wxOpenAuthorizerInfo.getHeadImg());
            wxApp.setQrCode(wxOpenAuthorizerInfo.getQrcodeUrl());
            wxApp.setPrincipalName(wxOpenAuthorizerInfo.getPrincipalName());
            wxApp.setSignature(wxOpenAuthorizerInfo.getSignature());
            wxApp.setAppType(WxConstant.WX_APP_TYPE_1);
            wxAppService.saveOrUpdate(wxApp);
            return R.ok();
        } catch (WxErrorException e) {
            e.printStackTrace();
            return WxReturnCode.wxErrorExceptionHandler(e);
        }
    }
}
